package jsu.yym.tiktok.controller;

import jsu.yym.tiktok.pojo.File;
import jsu.yym.tiktok.pojo.ResponseResult;
import jsu.yym.tiktok.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
public class fileController {
    @Autowired
    private FileMapper fileMapper;

    //新建文件夹
    @PostMapping("/file/add")
    public ResponseResult addFile(@RequestBody File file)
    {
        //判断重复
        File f = fileMapper.getVideoByUserNameAndState(file.getUsername(),file.getFileName());
        if (!Objects.isNull(f)) {
            return new ResponseResult(409,"重复创建");
        }
        int count = fileMapper.insert(file);
        if(count<=0)
            return new ResponseResult(503,"创建失败");
        return new ResponseResult(200,"创建成功");
    }

    //删除文件夹
    @PostMapping("/file/delete")
    public ResponseResult deleteFile(@RequestBody File file)
    {
        int count = fileMapper.deleteById(file);
        if(count<=0)
            return new ResponseResult(503,"删除失败");
        return new ResponseResult(200,"删除成功");
    }

    //修改文件夹名字
    @PostMapping("/file/update")
    public ResponseResult updateFile(@RequestBody File file)
    {
        int count = fileMapper.updateById(file);
        if(count<=0)
            return new ResponseResult(503,"修改失败");
        return new ResponseResult(200,"修改成功");
    }

    //获取用户的所有文件夹
    @GetMapping("/file/get")
    public ResponseResult getFile()
    {
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        List<File> files = fileMapper.getFileByUsername(id);
        if (Objects.isNull(files)) {
            return new ResponseResult(503,"获取失败");
        }
        return new ResponseResult(200,"获取成功",files);
    }
}
